package com.cloudsubassemblykafka10024.offset;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Properties;

/**
 * @Description: TODO
 * @Author zx
 * @Date 2024/12/25 17:40
 * @Version 1.0
 */
public class KafkaConsumerOffset_002 {

    public static void main(String[] args) {

        // 创建 Kafka Consumer
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.18.220:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group3");

        // 默认配置是latest
        // properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        // 如果 配置为 earliest，则从队列头开始消费
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        // 配置 自动提交 offset 的时间间隔 10s 提交一次
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 10000);
        // 配置自动提交 offset 为 false
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        // 偏移量自动提交
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);

        // 订阅主题
        kafkaConsumer.subscribe(Arrays.asList("messageDML003"));

        // 遍历消息队列
        while (true) {
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(30));
            if (!consumerRecords.isEmpty()) {
                Iterator<ConsumerRecord<String, String>> iterator = consumerRecords.iterator();
                while (iterator.hasNext()) {
                    // 获取消息
                    ConsumerRecord<String, String> record = iterator.next();
                    System.out.println("消息已消费");
                    System.out.println(record.topic() + ":" + record.partition() + ":" + record.offset() + ":" + record.key() + ":" + record.value() + ":" + record.timestamp());
                }
            }
        }
    }

}
